# -*- coding: utf-8 -*-
import datetime

from openerp import models, fields, api
from openerp.exceptions import Warning

class bc_payment(models.Model):
    _name = 'bc.payment'

    name = fields.Char()
    bussines_id = fields.Many2one('bc.bussines')
    company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id)
    dttrans = fields.Datetime(default=datetime.datetime.utcnow())
    state = fields.Selection([('draft', u'草稿'), ('audit', u'审核'), ('close', u'关闭')])
    decmoney = fields.Float()
    remark = fields.Text()
    audit_uid = fields.Many2one('res.users')
    audit_date = fields.Datetime()

    @api.model
    def create(self, vals):
        vals['name'] = self.env['ir.sequence'].get('bc.payment')
        vals['state'] = 'draft'
        return super(bc_payment, self).create(vals)
    
    # 僅能刪除草稿狀態的資料
    @api.multi
    def unlink(self):
       if self.state not in ('draft') :
          raise Warning(_('state {0} can not be delete'.format(self.state)))
       return super(bc_payment,self).unlink()    

    @api.model
    def btn_audit(self):
        self.write({'state': 'audit', 'audit_uid': self.env.user.id, 'audit_date': datetime.datetime.utcnow()})
        return True

    @api.model
    def btn_unaudit(self):
        self.write({'state': 'draft', 'audit_uid': False, 'audit_date': False})
        return True

    def get_bussines_total_Moeny(self, bussines_id):
        """
        返回用户交费的总金额
        :bussines_id bussines_id:
        :return: float 总金额额
        """
        return sum(payment.decmoney for payment in self.search([('bussines_id', '=', bussines_id)]))
